<?php

class Db
{
    private $host;
    private $user;
    private $pass;
    private $name;
    private $link;

    public function __construct($config)
    {
        $this->host = $config['host'];
        $this->user = $config['user'];
        $this->pass = $config['pass'];
        $this->name = $config['name'];
        $this->connectDb();
        $this->link->query("set names 'utf8'");
    }

    /**
     * @return
     */
    private function connectDb()
    {
        $this->link = new mysqli($this->host,$this->user,$this->pass,$this->name);
        if ($this->link->connect_errno) {
            echo '数据库连接失败';
            exit;
        }
        return $this->link;
    }

    public function getOne($table,$where,$field)
    {
        $sql = 'select '.$field.' from '.$table.' where '.$where;
        $result = $this->link->query($sql);
        return $result->fetch_assoc();
    }

    public function getMany($table,$where,$field)
    {
        $sql = 'select '.$field.' from '.$table.' where '.$where;
        $result = $this->link->query($sql);
        $rows = [];
        while($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
        return $rows;
    }

    public function deleteOne($table,$where)
    {
        $sql = 'delete from '.$table.' where '.$where;
        $result = $this->link->query($sql);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }


    public function insertOne($table,$field,$value)
    {
        $sql = 'insert into '.$table.' ('.$field.')'.' values ('.$value.')';
        //echo $sql;exit;
        $result = $this->link->query($sql);
        if ($result) {
            return $this->link->insert_id;
        } else {
            return false;
        }
    }

    public function query($sql)
    {
        return $this->link->query($sql);
    }

    public function close()
    {
        $this->link->close();
    }
}

// $db = new Db(['host'=>'localhost','user'=>'root','pass'=>'root','name'=>'capture']);
// $curr_id = 124;
// $tmp_result = $db->query("select id,img_path from capture where id < $curr_id order by id desc limit 1");
// $prev_info = $tmp_result->fetch_assoc();
// var_dump($prev_info);

